import cv2
import numpy as np
from matplotlib import pyplot as plt
import random

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文


# 添加高斯噪声\mean : 均值\var : 方差
def gasuss_noise(image, mean=0, var=0.02):
    image = np.array(image / 255, dtype=float)
    noise = np.random.normal(mean, var ** 0.5, image.shape)
    out = image + noise
    if out.min() < 0:
        low_clip = -1.
    else:
        low_clip = 0.
    out = np.clip(out, low_clip, 1.0)
    out = np.uint8(out * 255)
    return out


# prob:噪声比例
def sp_noise(image, prob):
    output = np.zeros(image.shape, np.uint8)
    thres = 1 - prob
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output


img = cv2.imread(r'img/img.png', 0)  # 参数0说明读入灰度图像

result1 = gasuss_noise(img)

result5 = sp_noise(img, 0.2)

plt.figure()

plt.subplot(2, 4, 1)
plt.axis('off')
plt.imshow(result1, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('添加高斯噪声图像')

# 处理结果=cv2.blur(原始图像,核大小)
# 核大小：以（宽度，高度）的元祖
# 效果：使图像变模糊啦。能处理被椒盐攻击过的照片。
result2 = cv2.blur(result1, (10, 10))
plt.subplot(2, 4, 2)
plt.axis('off')
plt.imshow(result2, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('均值滤波')

# 实现方法：medianBlur
# 目标图像=cv2.medianBlur(原始图像,intksize)
# intksize:核函数，必须为奇数.
result3 = cv2.medianBlur(result1, 5)
plt.subplot(2, 4, 3)
plt.axis('off')
plt.imshow(result3, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('中值滤波')

# 处理结果=cv2.GaussianBlur(原始图像src，核函数大小ksize，sigmaX)
# 核函数大小ksize：（N，N）必须是奇数
# sigmaX：控制x方向方差，控制权重,一般取0,它自己去计算方差。y轴方差和x一致
result4 = cv2.GaussianBlur(result1, (7, 7), 0)
plt.subplot(2, 4, 4)
plt.axis('off')
plt.imshow(result4, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('高斯滤波')

plt.subplot(2, 4, 5)
plt.axis('off')
plt.imshow(result5, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('添加椒盐噪声图像')

result6 = cv2.blur(result5, (10, 10))
plt.subplot(2, 4, 6)
plt.axis('off')
plt.imshow(result6, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('均值滤波')

result7 = cv2.medianBlur(result5, 5)
plt.subplot(2, 4, 7)
plt.axis('off')
plt.imshow(result7, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('中值滤波')

result8 = cv2.GaussianBlur(result5, (5, 5), 0)
plt.subplot(2, 4, 8)
plt.axis('off')
plt.imshow(result8, vmin=0, vmax=255, cmap=plt.cm.gray)
plt.title('高斯滤波')

plt.show()
